<template>
    <div id="authorization">
        <div class="top-bg align-center">
            <img src="./img/authorization.png" alt="">
            <span class=" s-18">VIP资源需要授权才能使用</span>
        </div>
        <el-form :model="authorization" :rules="rules" ref="authorization">
            <el-form-item prop="code">
                <el-input v-model.trim="authorization.code" @input="change" @contextmenu.native="showRightClickMenu" placeholder="输入授权码" @focus="focus" style="width:27.778vw;height:3.333vw;margin:0 auto"></el-input>
            </el-form-item>
        </el-form>
        <button :class="['at-btn', 'dis-button',{'use-btn':authorization.code}]" :disabled="!authorization.code" @click="authorize">授权</button>
        <div class="tips s-16 get-code" @click="switchCode">没有授权码？点击获取</div>
        <div class="s-12 flex-center t-color-c">您也可以通过累计平台积分兑换VIP资源使用权限&nbsp;&nbsp;&nbsp;&nbsp; <a class="toPoint" href="#" @click="$router.push({name:'point'})">查看详情</a></div>
    </div>
</template>

<script>
import redeem from '@/content/api/redeem'
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser'
import User from '@/content/api/user'
import { Book } from '../../../../../../static/lib/sqlite/model/Book'
import { Publisher } from '../../../../../../static/lib/sqlite/model/Publisher'
import { SqlLibBook } from "../../../../../../static/lib/sqlite/service/SqlLibBook";
import { updateUserMessage } from '../../../utils/event'
import bus from '../../../assets/js/bus'
import store from '@/content/store/index.js'
const cryUtil = require('../../../../../../static/utils/CrypUtil')
export default {
    inject: ['initPage', 'updateBookAuthorize', 'initPersonStatus'],
    props: ['bookId'],
    data () {
        let code = (rule, value, callback) => {
            let rex = new RegExp(/^[0-9a-z]{5,15}[0-9a-z]$/)
            console.log(rex.test(value))
            if (rex.test(value.replace(/\s/g, ''))) {
                callback()
            } else {
                this.isUse = false
                return callback(new Error('授权码错误，请检查后填写'))
            }
        }
        return {
            isUse: true,
            authorization: {
                code: ''
            },
            oldCode: '',
            rules: {
                code: { validator: code, trigger: 'submit' }
            }
        }
    },
    methods: {
        authorize () {
            let _this = this;
            this.$refs.authorization.validate(val => {
                if (val) {
                    User.authRedeemCode({
                        redeemCode: _this.authorization.code.replace(/\s/g, '')
                    }).then(async response => {
                        if (response.code == "0") {
                            let updateUser = await User.getUserInfo()
                            store.state.becomeVip = updateUser.returnValue.isVip
                            let sqlLib = SqlLib.getInstance(window.$DBDIR)
                            let user = SqlLibUser.queryCurrentUser(sqlLib)
                            let bookId = response.returnValue ? response.returnValue.bookId : ''
                            user.remainderDays = cryUtil.aesEncrypt(updateUser.returnValue.days + "", user.id + "", true);
                            user.vipType = cryUtil.aesEncrypt(updateUser.returnValue.isVip + "", user.id + "", true);

                            SqlLibBook.updateBookAuthorization(sqlLib, bookId);
                            sqlLib.updateObjectById(user)
                            _this.$message.success("授权成功！");
                            updateUserMessage()
                            bus.$emit("refreshHome")
                            _this.authorization.code = '';
                            if (bookId && bookId !== '' && bookId !== this.bookId) {
                                let newBook = new Book()
                                let newPubliser = new Publisher()
                                newBook.id = bookId
                                let book = sqlLib.selectObjectById(newBook)
                                let bookName = book.name || ''
                                let eduName = ''
                                if (book.publisherId) {
                                    newPubliser.id = book.publisherId
                                    eduName = sqlLib.selectObjectById(newPubliser).name
                                }
                                this.$dialog({
                                    cancel: '取消',
                                    confirm: '立即跳转',
                                    message: `${eduName}${bookName}授权成功是否立即跳转`,
                                    type: 'success'
                                }).then(() => {
                                    user.bookId = bookId
                                    sqlLib.updateObjectById(user)
                                    _this.initPersonStatus();
                                    _this.initPage()
                                })
                            } else {
                                sqlLib.updateObjectById(user)
                                _this.initPersonStatus();
                                _this.initPage()
                            }
                        } else {
                            _this.$message.warning("授权失败，请联系小美客服！");
                        }
                    }).catch(error => {
                        console.log(error)
                        _this.$message.warning("授权失败，请联系小美客服！");
                    })
                }
            })
        },
        //清除表单验证
        focus () {
            this.$refs.authorization.clearValidate()
        },
        change (val, oldval) {
            let trimVal = val.replace(/\s/g, '')
            if (trimVal.length === 0) {
                this.oldCode = ''
                return
            }
            if (trimVal.length > 16) {
                val = trimVal.substr(0, 16)
                this.oldCode = this.authorization.code = val.replace(/([^\s]{4})/g, '$1  ')
                return
            }
            if (val.length < this.oldCode.length) return
            this.oldCode = this.authorization.code = this.authorization.code.replace(/\s/g, '').replace(/([^\s]{4})/g, '$1  ')
        },
        switchCode () {
            this.$emit("getCode", "2");
        },
        showRightClickMenu () {
            console.log("I'm showRightClickMenu...")
            const { ipcRenderer } = require('electron');
            ipcRenderer.send('sigShowRightClickMenu');
        }
    }
}
</script>

<style lang="scss">
#authorization {
    width: 37.5vw;
    height: 27.778vw;
    background: rgba(255, 255, 255, 1);
    border-radius: 0.556vw;
    .top-bg {
        width: 37.5vw;
        height: 12.5vw;
        background-image: url(./img/author-bg.png);
        background-size: cover;
        border-radius: 0.556vw 0.556vw 0vw 0vw;
    }
    img {
        height: 6.736vw;
        width: 11.528vw;
        margin-bottom: 1.875vw;
    }
    .el-form {
        display: flex;
        justify-content: center;
    }
    .at-btn {
        margin: 0 auto;
        display: block;
        width: 11.111vw;
        height: 3.333vw;
        border-radius: 0.556vw;
        margin-top: 1vw;
    }
    .get-code {
        text-align: center;
        margin-top: 1vw;
    }
    .toPoint {
        color: #4894ff;
        text-decoration: underline;
        font-style: oblique;
    }
}
</style>
